package com.afd.ozblip.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.afd.ozblip.adapter.BusinessList2Adapter;
import com.afd.ozblip.entity.BusinessEntity;
import com.afd.ozblip.entity.CategoryEntity;
import com.afd.ozblip.net.HttpUtil;
import com.afd.ozblip.util.AsyncAction;
import com.afd.ozblip.util.AsyncLoadData;
import com.afd.ozblip.util.CollectionUtil;
import com.afd.ozblip.util.Constants;
import com.afd.ozblip.util.OzblipConfig;
import com.afd.ozblip.util.ParseJson;
import com.afd.ozblip.util.StringUtil;
import com.afd.ozblip.view.UIPullRefereshListView;
import com.afd.ozblip.view.UIPullRefereshListView.OnFooterLoadListener;
import com.afd.ozblip.view.UIPullRefereshListView.OnRefreshListener;
import com.alibaba.fastjson.JSON;
import com.google.android.gms.maps.model.LatLng;

import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

public class CityBusinessActivity extends BaseActivity {

	/****************** 视图变量 **************************/
	// private ViewGroup sortContainer;
	private LinearLayout areaFilterLayout;
	private LinearLayout conAreaLayout;
	private LinearLayout categoryFilterLayout;
	private RadioGroup categoryFilterLeftLayout;
	private FrameLayout categoryFilterRightLayout;
	private TextView areaTv;
	private TextView categoryTv;
	private TextView sortTv;
	private LinearLayout conCategoryLayout;
	private LinearLayout sortFilterLayout;
	private LinearLayout conSortLayout;
	private LinearLayout commonRightLayout;

	private UIPullRefereshListView businessListView;
	private ListView areaListView;
	protected Animation animPushTopIn;
	protected Animation animPushTopOut;
	/****************** 数据条件变量 ***********************/
	// 父级类型名称
	private String parentClassName;
	// 子级类型名称
	private String childClassName;
	// 区域编号
	private String areaId;
	// 排序方式
	private int sortVal;
	/****************** 其它变量 **************************/
	private List<BusinessEntity> businessList;
	private BusinessList2Adapter businessListAdapter;
	private int nowPage = 1;
	private int totalPage;
	// 总分类长度
	private int classLen;
	private int parentClassIndex;
	private List<CategoryEntity> categoryList;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.city_business);
		// 启动返回功能
		toBack();
		// 寻找视图
		findViews();
		// 设置监听
		setListeners();
		// 获取参数
		getBundle();
		// 初始化分类条件
		initCategory();
		// 获取区域列表数据
		requestAreaListData();
		// 获取列表数据
		this.businessListView.referesh();

	}

	/**
	 * 寻找视图
	 */
	public void findViews() {
		this.commonRightLayout = (LinearLayout) findViewById(R.id.ll_common_right);
		this.areaListView = (ListView) findViewById(R.id.lv_area_list);

		this.areaTv = (TextView) findViewById(R.id.tv_conditon_area);
		this.categoryTv = (TextView) findViewById(R.id.tv_conditon_category);
		this.sortTv = (TextView) findViewById(R.id.tv_conditon_sort);
		this.areaFilterLayout = (LinearLayout) findViewById(R.id.ll_conditon_filter_area);
		this.conAreaLayout = (LinearLayout) findViewById(R.id.ll_conditon_area);
		this.categoryFilterLayout = (LinearLayout) findViewById(R.id.ll_conditon_filter_category);
		this.conCategoryLayout = (LinearLayout) findViewById(R.id.ll_conditon_category);
		this.sortFilterLayout = (LinearLayout) findViewById(R.id.ll_conditon_filter_sort);
		this.conSortLayout = (LinearLayout) findViewById(R.id.ll_conditon_sort);
		// 距离选择视图
		this.businessListView = (UIPullRefereshListView) findViewById(R.id.lv_nearby_businessList);
		this.animPushTopIn = AnimationUtils.loadAnimation(this,
				R.anim.push_top_in);
		this.animPushTopOut = AnimationUtils.loadAnimation(this,
				R.anim.push_top_out);
		// initContainer();
	}

	private void showFilter(LinearLayout layout) {
		layout.setVisibility(0);
		layout.startAnimation(this.animPushTopIn);
	}

	private void hideFilter(LinearLayout layout) {
		layout.startAnimation(this.animPushTopOut);
		layout.setVisibility(8);
	}

	/**
	 * 设置监听
	 */
	public void setListeners() {

		View.OnClickListener nearByBusinessClick = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				switch (v.getId()) {
				case R.id.ll_common_right:
					Intent settingIntent = new Intent(
							CityBusinessActivity.this, NearbyMapActivity.class);
					String latlngList = getBusinessLatLngList();
					settingIntent.putExtra("LatLngJsonList", latlngList);
					startActivity(settingIntent);
					break;
				case R.id.ll_conditon_area:
					categoryFilterLayout.setVisibility(8);
					sortFilterLayout.setVisibility(8);
					conAreaLayout.setBackgroundColor(getResources().getColor(
							R.color.condition_select_bg));
					conCategoryLayout.setBackgroundColor(getResources()
							.getColor(R.color.transparent));
					conSortLayout.setBackgroundColor(getResources().getColor(
							R.color.transparent));
					if (areaFilterLayout.getVisibility() == 8) {
						showFilter(areaFilterLayout);
					} else {
						hideFilter(areaFilterLayout);
					}
					break;
				case R.id.ll_conditon_category:
					areaFilterLayout.setVisibility(8);
					sortFilterLayout.setVisibility(8);
					conAreaLayout.setBackgroundColor(getResources().getColor(
							R.color.transparent));
					conCategoryLayout.setBackgroundColor(getResources()
							.getColor(R.color.condition_select_bg));
					conSortLayout.setBackgroundColor(getResources().getColor(
							R.color.transparent));
					if (categoryFilterLayout.getVisibility() == 8) {
						showFilter(categoryFilterLayout);
					} else {
						hideFilter(categoryFilterLayout);
					}
					break;
				case R.id.ll_conditon_sort:
					areaFilterLayout.setVisibility(8);
					categoryFilterLayout.setVisibility(8);
					conAreaLayout.setBackgroundColor(getResources().getColor(
							R.color.transparent));
					conCategoryLayout.setBackgroundColor(getResources()
							.getColor(R.color.transparent));
					conSortLayout.setBackgroundColor(getResources().getColor(
							R.color.condition_select_bg));
					if (sortFilterLayout.getVisibility() == 8) {
						showFilter(sortFilterLayout);
					} else {
						hideFilter(sortFilterLayout);
					}
					break;

				default:
					break;
				}
			}
		};
		this.commonRightLayout.setOnClickListener(nearByBusinessClick);
		this.conAreaLayout.setOnClickListener(nearByBusinessClick);
		this.conCategoryLayout.setOnClickListener(nearByBusinessClick);
		this.conSortLayout.setOnClickListener(nearByBusinessClick);
		this.businessListAdapter = new BusinessList2Adapter(
				CityBusinessActivity.this);
		businessList = new ArrayList<BusinessEntity>();
		this.businessListAdapter.addItems(businessList);
		this.businessListView.setAdapter(this.businessListAdapter);
		this.businessListView.setonRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				nowPage = 1;
				requestCityBusinessListData(true);
			}
		});
		this.businessListView
				.setOnFooterLoadListener(new OnFooterLoadListener() {

					@Override
					public void onLoad() {
						if (nowPage < totalPage) {
							requestCityBusinessListData(false);
							nowPage = nowPage + 1;
							businessListView.nowPage = nowPage;
						}
					}
				});

		this.businessListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> itemView, View arg1,
					int parameInt, long arg3) {
				Intent businessIntent = new Intent(CityBusinessActivity.this,
						BusinessInfoActivity.class);
				BusinessEntity business = businessListAdapter.dataList
						.get(parameInt - 1);
				businessIntent.putExtra("businessInfo", business);
				startActivity(businessIntent);
			}
		});
	}

	/**
	 * TODO 获取传递的参数
	 */
	private void getBundle() {
		Intent intent = getIntent();
		areaId = intent.getStringExtra("areaId");
		parentClassName = intent.getStringExtra("parClass");
		childClassName = intent.getStringExtra("chiClass");
	}

	private void setViews() {
		if (!StringUtil.isNullOrEmpty(childClassName)) {
			this.categoryTv.setText(childClassName);
		} else {
			this.categoryTv.setText(parentClassName);
		}

	}

	private void initCategory() {
		this.categoryFilterLeftLayout = (RadioGroup) findViewById(R.id.ll_conditon_filter_category_left);
		this.categoryFilterRightLayout = (FrameLayout) findViewById(R.id.ll_conditon_filter_category_right);

		LayoutInflater inflater = LayoutInflater.from(this);
		categoryList = Constants.getCategoryList();
		classLen = categoryList.size();
		View.OnClickListener leftClick = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				int index = Integer.parseInt(v.getTag().toString());
				for (int i = 0, len = classLen; i < len; i++) {
					categoryFilterRightLayout.getChildAt(i).setVisibility(8);
				}
				categoryFilterRightLayout.getChildAt(index).setVisibility(0);
			}
		};
		View.OnClickListener rightClick = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				int index = Integer.parseInt(v.getTag().toString());
				parentClassName = categoryList.get(parentClassIndex)
						.getParentClassName();
				if ("热门分类".equals(parentClassName)) {
					parentClassName = "";
				}
				childClassName = categoryList.get(parentClassIndex)
						.getChildClassList().get(index);
				conAreaLayout.setBackgroundColor(getResources().getColor(
						R.color.transparent));
				if (categoryFilterLayout.getVisibility() == 8) {
					showFilter(categoryFilterLayout);
				} else {
					hideFilter(categoryFilterLayout);
				}
				setViews();
				// dataTipTv.setVisibility(8);
				businessListView.referesh();
			}
		};
		for (int i = 0, len = categoryList.size(); i < len; i++) {
			View leftView = inflater.inflate(R.layout.category_left_item, null);
			RadioButton leftRB = (RadioButton) leftView;
			String parentCN = categoryList.get(i).getParentClassName();
			leftRB.setText(parentCN);
			leftRB.setId(i);
			if ("热门分类".equals(parentCN)) {
				leftRB.setChecked(true);
			}
			// 设置drawableleft
			BitmapDrawable leftbd = getListIco(i);
			leftRB.setCompoundDrawablesWithIntrinsicBounds(leftbd, null, null,
					null);
			// 设置tag
			leftRB.setTag(i);
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.MATCH_PARENT,
					LinearLayout.LayoutParams.WRAP_CONTENT);
			leftView.setOnClickListener(leftClick);
			this.categoryFilterLeftLayout.addView(leftView, lp);
			LinearLayout ll = new LinearLayout(this);
			ll.setLayoutParams(new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.MATCH_PARENT,
					LinearLayout.LayoutParams.MATCH_PARENT));
			ll.setOrientation(LinearLayout.VERTICAL);
			ll.setVisibility(i == 0 ? 0 : 8);
			List<String> childClassList = categoryList.get(i)
					.getChildClassList();
			for (int j = 0, childLen = childClassList.size(); j < childLen; j++) {
				View rightView = inflater.inflate(R.layout.category_right_item,
						null);
				rightView.setBackgroundResource(R.drawable.ll_bg_selector);
				rightView.setTag(j);
				rightView.setOnClickListener(rightClick);
				TextView rightTv = (TextView) rightView
						.findViewById(R.id.tv_category_right);
				rightTv.setText(childClassList.get(j));
				ll.addView(rightView, lp);
			}
			this.categoryFilterRightLayout.addView(ll);
		}
	}

	private BitmapDrawable getListIco(int index) {
		Resources res = getResources();
		BitmapDrawable bd = null;
		Bitmap bm = null;
		switch (index) {
		case 0:
			bm = BitmapFactory.decodeResource(res, R.drawable.list_ico1);
			bd = new BitmapDrawable(res, bm);
			break;
		case 1:
			bm = BitmapFactory.decodeResource(res, R.drawable.list_ico2);
			bd = new BitmapDrawable(res, bm);
			break;
		case 2:
			bm = BitmapFactory.decodeResource(res, R.drawable.list_ico3);
			bd = new BitmapDrawable(res, bm);
			break;
		case 3:
			bm = BitmapFactory.decodeResource(res, R.drawable.list_ico4);
			bd = new BitmapDrawable(res, bm);
			break;
		case 4:
			bm = BitmapFactory.decodeResource(res, R.drawable.list_ico5);
			bd = new BitmapDrawable(res, bm);
			break;
		case 5:
			bm = BitmapFactory.decodeResource(res, R.drawable.list_ico6);
			bd = new BitmapDrawable(res, bm);
			break;
		case 6:
			bm = BitmapFactory.decodeResource(res, R.drawable.list_ico7);
			bd = new BitmapDrawable(res, bm);
			break;
		case 7:
			bm = BitmapFactory.decodeResource(res, R.drawable.list_ico8);
			bd = new BitmapDrawable(res, bm);
			break;

		default:
			break;
		}
		return bd;
	}

	/**
	 * 获取区域列表数据
	 */
	private void requestAreaListData() {
		areaListView.setAdapter(new SimpleAdapter(this, areaList,
				R.layout.area_item, new String[] { "areaName" },
				new int[] { R.id.tv_area_item_name }));
		areaListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int parameInt, long arg3) {
				HashMap<String, Object> areaMap = areaList.get(parameInt);
				areaId = (String) areaMap.get("areaId");
				areaTv.setText(areaMap.get("areaName").toString());
				conAreaLayout.setBackgroundColor(getResources().getColor(
						R.color.transparent));
				if (areaFilterLayout.getVisibility() == 8) {
					showFilter(areaFilterLayout);
				} else {
					hideFilter(areaFilterLayout);
				}
				businessListView.referesh();
			}
		});
	}

	/**
	 * TODO 获取全城商家列表数据
	 */
	private void requestCityBusinessListData(final boolean isReferesh) {

		AsyncLoadData ald = new AsyncLoadData(this, "", new AsyncAction() {

			@Override
			public void doLoad() throws Exception {
				// 获取提交参数
				Map<String, Object> nearbyBusinessParamMap = new HashMap<String, Object>();
				nearbyBusinessParamMap.put("parClass", parentClassName);
				nearbyBusinessParamMap.put("chiClass", childClassName);
				nearbyBusinessParamMap.put("userLongitude", "29.57");
				nearbyBusinessParamMap.put("userDimension", "106.52");
				nearbyBusinessParamMap.put("city", commonNowCityName);
				nearbyBusinessParamMap.put("area", areaId);
				nearbyBusinessParamMap.put("pageCnt", nowPage);
				nearbyBusinessParamMap.put("pageRow",
						OzblipConfig.seller_pageSize);
				nearbyBusinessParamMap.put("sort", "1");
				nearbyBusinessParamMap.put("language", commonLanguage);
				// 发送请求
				byte[] commentItemList = HttpUtil.requestByPost(
						CityBusinessActivity.this, Constants.SELLER_LIST_API,
						nearbyBusinessParamMap);
				if (commentItemList != null) {
					Map<String, Object> resultMap = new ParseJson()
							.parseBusinessListJson(commentItemList);
					businessList = (List<BusinessEntity>) resultMap.get("data");
					if (isReferesh) {
						totalPage = (Integer) resultMap.get("totalPage");
					}
				}
			}

			@Override
			public void loadEnd() throws Exception {
				if (isReferesh) {
					businessListView.onRefreshComplete();
					businessListAdapter.removeAllItem();
					businessListView.nowPage = nowPage;
					businessListView.totalPage = totalPage;
				} else {
					businessListView.loadComplete();
				}
				businessListAdapter.addItems(businessList);
				businessListAdapter.notifyDataSetChanged();

			}

		});
		ald.execute(0);
	}

	/**
	 * 调用评论列表适配器
	 */
	public void setTopListAdapter() {
		if (CollectionUtil.UnNullAndZero(businessList)) {
			this.businessListAdapter = new BusinessList2Adapter(
					CityBusinessActivity.this);
			this.businessListAdapter.addItems(businessList);
			this.businessListView.setAdapter(this.businessListAdapter);
		}
	}

	/**
	 * 获取当前商家经纬度列表
	 */
	private String getBusinessLatLngList() {
		List<LatLng> llList = new ArrayList<LatLng>();
		for (int i = 0, len = this.businessListAdapter.dataList.size(); i < len; i++) {
			BusinessEntity be = this.businessListAdapter.dataList.get(i);
			LatLng ll = new LatLng(Double.parseDouble(be.getSellerLongitude()),
					Double.valueOf(be.getSellerDimension()));
			llList.add(ll);
		}
		String json = JSON.toJSONString(llList);
		return json;
	}
}